package com.googlecode.cachebrowser.ui.preferences;

import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.PathEditor;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

import com.googlecode.cachebrowser.Activator;

/**
 * This class represents a preference page that
 * is contributed to the Preferences dialog. By 
 * subclassing <samp>FieldEditorPreferencePage</samp>, we
 * can use the field support built into JFace that allows
 * us to create a page that is small and knows how to 
 * save, restore and apply itself.
 * <p>
 * This page is used to modify preferences only. They
 * are stored in the preference store that belongs to
 * the main plug-in class. That way, preferences can
 * be accessed directly via the preference store.
 */

public class PreferencePage
	extends FieldEditorPreferencePage
	implements IWorkbenchPreferencePage {
	
	private StringFieldEditor serverURL;
	private PathEditor classpath;

	public PreferencePage() {
		super(GRID);
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
		setDescription("Main Preferences");
	}
	
	/**
	 * Creates the field editors. Field editors are abstractions of
	 * the common GUI blocks needed to manipulate various types
	 * of preferences. Each field editor knows how to save and
	 * restore itself.
	 */
	public void createFieldEditors() {		
		serverURL = new StringFieldEditor("Server Path", "Server path", getFieldEditorParent());
		classpath = new PathEditor("Classpath Entries", "Classpath entries", "Classpath entries ", getFieldEditorParent()); 
		
		addField(serverURL);
		addField(classpath);
	}

	@Override
	public void propertyChange(PropertyChangeEvent event) {
		super.propertyChange(event);
		if( event.getProperty().equals(FieldEditor.VALUE) ) {
			checkState();
		}
	}

	@Override
	protected void checkState() {
		super.checkState();
		String url = serverURL.getStringValue();
		if( url == null || 
			url.length() == 0 ||
			!url.matches("\\w+:\\d{1,5}")){
			setErrorMessage("Invalid server URL");
			setValid(false);
		} else {
			setValid(true);
			setErrorMessage(null);
		}
	}

	public void init(IWorkbench workbench) {
		
	}
}